<template>
  <div class="course-section">
    <el-card>
      <div slot="header" style="display: flex; justify-content: space-between">
        课程名称
        <el-button type="primary" @click="openAddPart">添加阶段</el-button>
      </div>
      <el-tree
        :data="sections"
        :props="defaultProps"
        draggable
        :allow-drop="handleAllowDrop"
        @node-drop="handleSort"
      >
        <div slot-scope="{ node, data }" class="inner">
          <span>{{ node.label }}</span>
          <span class="actions" v-if="data.sectionName">
            <el-button @click="handleEditSection(data)"> 编辑</el-button>
            <el-button @click="openAddTheme(data)">添加课时</el-button>
            <el-select
              @change="(e) => selectSectionChange(e, data)"
              v-model="data.status"
              placeholder="请选择"
              style="margin-left: 10px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </span>
          <span class="actions" v-else>
            <el-button @click="handleEditTheme(data)"> 编辑</el-button>
            <el-button
              @click="
                $router.push({
                  name: 'video-course',
                  params: { courseId },
                })
              "
              >上传视频</el-button
            >
            <el-select
              @change="(e) => selectChange(e, data)"
              v-model="data.status"
              placeholder="请选择"
              style="margin-left: 10px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </span>
        </div>
      </el-tree>
    </el-card>

    <el-dialog
      title="添加课程阶段"
      :visible.sync="addPartDialogVisible"
      :before-close="handleClose"
      width="50%"
    >
      <el-form ref="form">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="addPart.courseName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="addPart.sectionName"></el-input>
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input type="textarea" v-model="addPart.description"></el-input>
        </el-form-item>
        <el-form-item label="章节排序" prop="orderNum">
          <el-input-number v-model="addPart.orderNum"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button @click="addPartDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddPartSubmit"
            >确认</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="添加课时阶段"
      :visible.sync="addThemeDialogVisible"
      :before-close="handleThemeClose"
      width="50%"
    >
      <el-form ref="form">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="lesson.courseName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="lesson.sectionName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="课时名称" prop="theme">
          <el-input type="textarea" v-model="lesson.theme"></el-input>
        </el-form-item>
        <el-form-item label="时长" prop="duration">
          <el-input v-model="lesson.duration">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否开放试听">
          <el-switch
            v-model="lesson.isFree"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
        <el-form-item label="课时排序" prop="orderNum">
          <el-input-number v-model="lesson.orderNum"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button @click="addThemeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddLessonSubmit"
            >确认</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  saveOrUpdateLesson,
  getCourseById,
  getBySectionId,
  getByIdLesson,
} from "@/services/course";
import { Form } from "element-ui";
export default Vue.extend({
  name: "CourseSection",
  props: {
    courseId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      sections: [],
      defaultProps: {
        children: "lessonDTOS",
        label(data: unknown) {
          return data.sectionName || data.theme;
        },
      },
      addPart: {
        courseId: 0,
        courseName: "",
        sectionName: "",
        description: "",
        orderNum: 0,
        status: 0,
      },
      lesson: {
        // id: 0,
        courseId: 0,
        courseName: "",
        sectionName: "",
        sectionId: 0,
        theme: "",
        duration: 0,
        isFree: true,
        orderNum: 0,
        status: 0,
      },
      options: [
        {
          label: "已隐藏",
          value: 0,
        },
        {
          label: "待更新",
          value: 1,
        },
        {
          label: "已更新",
          value: 2,
        },
      ],
      addPartDialogVisible: false,
      addThemeDialogVisible: false,
    };
  },
  created() {
    this.loadSection();
  },
  methods: {
    async loadSection() {
      const [a, b] = await Promise.all([
        getSectionAndLesson(this.courseId),
        getCourseById(this.courseId),
      ]);
      this.sections = a.data.data;
      this.addPart.courseName = b.data.data.courseName;
    },
    async handleAddPartSubmit() {
      this.addPart.courseId = this.courseId as unknown;
      const { data } = await saveOrUpdateSection(this.addPart);
      if (data.code === "000000") {
        this.$message.success("操作成功");
        this.loadSection();
        this.addPartDialogVisible = false;
        this.addPart = {
          courseId: this.addPart.courseId,
          courseName: this.addPart.courseName,
          sectionName: "",
          description: "",
          orderNum: 0,
          status: 0,
        };
        (this.$refs.form as Form).resetFields();
      }
    },
    async handleAddLessonSubmit() {
      const { data } = await saveOrUpdateLesson(this.lesson);
      if (data.code === "000000") {
        this.$message.success("操作成功");
        this.loadSection();
      }
    },
    openAddPart() {
      this.addPartDialogVisible = true;
    },
    openAddTheme(section: unknown) {
      this.addThemeDialogVisible = true;
      this.lesson.sectionId = section.id;
      this.lesson.courseName = this.addPart.courseName;
      this.lesson.sectionName = section.sectionName;
      this.lesson.courseId = this.courseId as unknown;
    },
    handleClose() {
      this.addPart = {
        courseId: this.addPart.courseId,
        courseName: this.addPart.courseName,
        sectionName: "",
        description: "",
        orderNum: 0,
        status: 0,
      };
      this.addPartDialogVisible = false;
    },
    handleThemeClose() {
      this.addThemeDialogVisible = false;
    },
    async handleEditSection(data: unknown) {
      this.addPartDialogVisible = true;
      const { data: sectionData } = await getBySectionId(data.id);
      this.addPart = {
        ...sectionData.data,
        courseName: this.addPart.courseName,
      };
    },
    async handleEditTheme(data: unknown) {
      this.addThemeDialogVisible = true;
      const { data: lessonData } = await getByIdLesson(data.id);
      const { data: sectionData } = await getBySectionId(
        lessonData.data.sectionId
      );
      this.lesson = {
        ...lessonData.data,
        courseName: this.addPart.courseName,
        sectionName: sectionData.data.sectionName,
        courseId: this.courseId,
      };
    },
    async selectChange(e: unknown, _data: unknown) {
      const { data: lessonData } = await getByIdLesson(_data.id);
      const { data: sectionData } = await getBySectionId(
        lessonData.data.sectionId
      );
      this.lesson = {
        ...lessonData.data,
        courseName: this.addPart.courseName,
        sectionName: sectionData.data.sectionName,
        courseId: this.courseId,
        status: e,
      };
      const { data } = await saveOrUpdateLesson(this.lesson);
      if (data.code === "000000") {
        this.$message.success("操作成功");
      }
    },
    async selectSectionChange(e: unknown, _data: unknown) {
      this.addPart.courseId = this.courseId as unknown;
      const { data: sectionData } = await getBySectionId(_data.id);
      this.addPart = {
        ...sectionData.data,
        courseName: this.addPart.courseName,
        status: e,
      };
      const { data } = await saveOrUpdateSection(this.addPart);
      if (data.code === "000000") {
        this.$message.success("操作成功");
      }
    },
    handleAllowDrop(draggingNode: unknown, dropNode: unknown, type: unknown) {
      // 拖动的节点
      // 放置目标的节点
      // prev inner next
      return (
        draggingNode.data.sectionId === dropNode.data.sectionId &&
        type !== "inner"
      );
    },
    async handleSort(dragNode: unknown, dropNode: unknown, type: unknown, event: unknown) {
      // 直接拿列表数据update this.sections
      // dropNode.parent.childrenNodes
      try {
        await Promise.all(
          dropNode.parent.childNodes.map((item: unknown, index: number) => {
            if (dragNode.data.lessonDTOS) {
              saveOrUpdateSection({
                id: item.data.id,
                orderNum: index + 1,
              });
            } else {
              return saveOrUpdateLesson({
                id: item.data.id,
                orderNum: index + 1,
              });
            }
          })
        );
        this.$message.success("排序成功");
      } catch (error) {
        this.$message.error("排序失败");
      }
    },
  },
});
</script>

<style lang="scss" scoped>
.inner {
  display: flex;
  flex: 1;
  padding: 10px;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px splid #ebeef5;
}
::v-deep .el-tree-node__content {
  height: auto;
}
</style>